<template>
  <n-modal
    v-model:show="getProps.modalData.show"
    class="custom-card"
    preset="card"
    :style="{ width: '900px' }"
    :bordered="false"
    :segmented="{
      content: true,
      footer: true
    }"
    :mask-closable="false"
  >
    <template #header>
      <div>批量修改一键起量</div>
      <n-text style="font-size: 14px">已选{{ getProps.modalData?.adgroupIdList?.length }}个广告</n-text>
    </template>
    <n-space vertical>
      <n-radio-group v-model:value="form.type">
        <n-radio key="统一修改" :value="1">统一修改</n-radio>
        <n-radio key="分别修改" :value="2">分别修改</n-radio>
      </n-radio-group>
      <n-data-table
        ref="tableRef"
        size="small"
        :data="getProps.modalData.checkedData"
        :columns="columns"
        :row-key="(row) => row.id"
        row-class-name="text-sm"
        max-height="infinite"
      />
      <n-space justify="end">
        <x-button @click="handleCancel">取消</x-button>
        <x-button :loading="loading" type="primary" @click="handleSave">确定</x-button>
      </n-space>
    </n-space>
  </n-modal>
</template>

<script setup lang="ts">
  import { computed, h, onMounted, reactive, ref, watch } from 'vue'
  import { XButton, XForm } from '@/components'

  import { NModal, NSpace, NInputNumber, NRadioGroup, NRadio, useMessage, NSwitch, NText, NDataTable } from 'naive-ui'
  import { useStore } from '@/store'
  import { useRoute } from 'vue-router'
  import { defineProps, defineEmits } from 'vue'
  const route = useRoute()
  const emit = defineEmits(['success'])
  const message = useMessage()
  const store = useStore()
  const accountCode = computed(() => {
    return route.query.accountCode
  })
  const loading = ref(false)
  const props = defineProps({
    modalData: {
      type: Object,
      default: () => ({})
    }
  })
  const getProps = reactive(props)
  const form = ref({
    accountCode: route.query.accountCode,
    type: 1
  })
  const columns = computed(() => {
    const arr = [
      {
        title: '广告名称',
        key: 'adgroupName',
        width: 100,
        render(row: any) {
          return h(NSpace, { vertical: true }, () => [h(NText, {}, () => row.adgroupName)])
        }
      },
      {
        title: '原设置',
        key: 'accountName',
        width: 100,
        render(row: any) {
          return h(NSpace, { vertical: true }, () => [
            h(NText, {}, () => (row.autoAcquisitionEnabled === 1 ? '已开启' : '未开启')),
            row.autoAcquisitionEnabled === 1 ? h(NText, {}, () => `，起量预算${row.autoAcquisitionBudget}`) : null
          ])
        }
      },
      form.value.type === 2
        ? {
            title: '修改一键起量',
            key: 'autoAcquisitionEnabled',
            width: 100,
            render(row: any) {
              return h(NSpace, { vertical: true }, () => [
                h(NSpace, { align: 'center' }, () => [
                  h(NSwitch, {
                    value: row.autoAcquisitionEnabled,
                    checkedValue: 'AD_STATUS_NORMAL',
                    uncheckedValue: 'AD_STATUS_SUSPEND',
                    onUpdateValue(v: any) {
                      row.autoAcquisitionEnabled = v
                    }
                  }),
                  h(NText, {}, () => (row.autoAcquisitionEnabled !== 'AD_STATUS_NORMAL' ? '关闭' : '开启'))
                ]),
                row.autoAcquisitionEnabled === 'AD_STATUS_NORMAL'
                  ? h(NInputNumber, {
                      showButton: false,
                      value: row.autoAcquisitionBudget,
                      min: 200,
                      max: 100000,
                      precision: 2,
                      suffix: () => {
                        return h(NText, {}, () => '元')
                      },
                      onUpdateValue(v: number) {
                        row.autoAcquisitionBudget = v
                      }
                    })
                  : null,
                row.autoAcquisitionEnabled === 'AD_STATUS_NORMAL'
                  ? h(NText, {}, () => '起量预算范围200~100,000元，不能低于出价')
                  : null
              ])
            }
          }
        : {
            title: '修改一键起量',
            key: 'autoAcquisitionEnabled',
            rowSpan: (rowData: any, rowIndex: number) => (rowIndex === 0 ? getProps.modalData.checkedData.length : 1),
            width: 100,
            render(row: any) {
              return h(NSpace, { vertical: true }, () => [
                h(NSpace, { align: 'center' }, () => [
                  h(NSwitch, {
                    value: row.autoAcquisitionEnabled,
                    checkedValue: 'AD_STATUS_NORMAL',
                    uncheckedValue: 'AD_STATUS_SUSPEND',
                    onUpdateValue(v: any) {
                      row.autoAcquisitionEnabled = v
                    }
                  }),
                  h(NText, {}, () => (row.autoAcquisitionEnabled !== 'AD_STATUS_NORMAL' ? '关闭' : '开启'))
                ]),
                row.autoAcquisitionEnabled === 'AD_STATUS_NORMAL'
                  ? h(NInputNumber, {
                      showButton: false,
                      value: row.autoAcquisitionBudget,
                      min: 200,
                      max: 100000,
                      precision: 2,
                      suffix: () => {
                        return h(NText, {}, () => '元')
                      },
                      onUpdateValue(v: number) {
                        row.autoAcquisitionBudget = v
                      }
                    })
                  : null,
                row.autoAcquisitionEnabled === 'AD_STATUS_NORMAL'
                  ? h(NText, {}, () => '起量预算范围200~100,000元，不能低于出价')
                  : null
              ])
            }
          }
    ]
    return arr
  })
  onMounted(() => {})
  async function handleSave() {
    const checkedData = getProps.modalData.checkedData
    const adgroupList: {
      accountCode: any
      outAdgroupId: any
      configuredStatus: string
      autoAcquisitionBudget: number
    }[] = []
    checkedData.forEach((item: any) => {
      adgroupList.push({
        accountCode: item.accountCode,
        outAdgroupId: item.adgroupId,
        configuredStatus: item.autoAcquisitionEnabled,
        bidAmount: form.value.type === 1 ? checkedData?.[0]?.autoAcquisitionBudget : item.autoAcquisitionBudget
      })
    })
    const params = {
      adgroupList: adgroupList
    }
    loading.value = true
    await store.dispatch('intelligent/gdtBatchAcquisition', params).then((res) => {
      message.success(`${res.data.successNum}个广告修改成功`)
    })
    loading.value = false
    emit('success')
    getProps.modalData.show = false
  }
  function handleCancel() {
    getProps.modalData.show = false
  }
</script>

<style scoped lang="scss">
  .tips {
    margin-top: 20px;
  }
  .max-cost {
    padding: 10px 0;
    text-align: center;
  }
</style>
